% clc;clear;close all;
% load('testdata_pll_5.mat');
% PLOT_LEN = 1200;
% ZERO_LEN = 0;%0 is the best fine tune
% 
% signal_rx = floor(signal);
% % signal_rx = floor(signal(1:20000));
% % signal_rx = repmat(signal_rx,1,25);
% % signal_rx = reshape(signal_rx,[],1);
% figure(1);subplot(311);plot((0:PLOT_LEN-1)/60e6,imag(signal_rx(1:PLOT_LEN)));
% figure(2);subplot(311);plot((0:PLOT_LEN-1)/60e6,real(signal_rx(1:PLOT_LEN)));
% 
% signal_rx = downsample([zeros(ZERO_LEN,1);signal_rx], 6);
% signal_rx(1:51) = 0;
% figure(1);subplot(312);plot((0:PLOT_LEN/6-1)/10e6,imag(signal_rx(1:PLOT_LEN/6)),'-*');
% figure(2);subplot(312);plot((0:PLOT_LEN/6-1)/10e6,real(signal_rx(1:PLOT_LEN/6)),'-*');
% 
% rcos_fir = round(1.15 * rcosdesign(0.5, 6, 4, 'sqrt') * 2^15);
% signal_rx = floor(filter(rcos_fir, 1, signal_rx) / (2^16));
% signal_rx = [0;signal_rx];
% figure(1);subplot(313);plot((0:PLOT_LEN/6-1)/10e6,imag(signal_rx(1:PLOT_LEN/6)),'-*');
% figure(2);subplot(313);plot((0:PLOT_LEN/6-1)/10e6,real(signal_rx(1:PLOT_LEN/6)),'-*');

%% Carrier Synchronization and Bit Synchronization
PllParams = PllInit();
signal_rx = rx_shape(rx_index:end);
res = [];
for index_data = 1:length(signal_rx)
    temp = signal_rx(index_data);
    % load pll demodulation data for farrow interpolation
    PllParams.phase = PllParams.phase + PllParams.FTW(end);
    
    input = signal_rx(index_data) * exp(-1i*2*pi*PllParams.phase/(2^32));
    res= [res;input];
    % pll error calculation
    PllParams.phase_error = imag(input)*sign(real(input)) - real(input)*sign(imag(input));
    % pll loop filter
    PllParams.loopfilter = PllParams.loopfilter + PllParams.phase_error;
    PllParams.FTW(end) = floor(PllParams.loopfilter*2^-2) + floor(PllParams.phase_error*2^10);
    
    PllParams.watch.phase = [PllParams.watch.phase,PllParams.phase];
    PllParams.watch.phase_error = [PllParams.watch.phase_error,PllParams.phase_error];
    PllParams.watch.loopfilter = [PllParams.watch.loopfilter,PllParams.loopfilter];
%     PllParams.watch.FTW = [PllParams.watch.FTW,PllParams.FTW];
end

%% ------------------------------Debug-----------------------------------------
figure;plot(PllParams.watch.loopfilter)
figure;plot(res,'*');
figure;plot(cos(PllParams.watch.phase));